﻿"""
获取上传的ini配置文件的位置信息，并将标准件的电压，电流写进新的配置文件
"""
import os
import shutil
import pyodbc
from datetime import datetime
# 导入自制模块
from sortingdataprocess import *
from setiniconfig import *
from getcobspec import *


def config_precal(form1_infos, cnxn, logger):
    """
    1 进行查询,数据库中工单号对应的标准件与输入标准件型号是否对应,CF2,CF3是否有效
    2 查询标准件是否存在有效数据
    3 查询工单的lotID在数据库中是否存在,存在+1,不存在设置为1
    4 创建上传文件路径,并读取上传的配置文件进行电流.电压的修改
    5 将form1_infos中的数据,存入数据库的Precal_Info1中
    """
    flash_result = {}
    initconf_path = None
    lotID = None
    cursor = cnxn.cursor()
    cursor.fast_executemany = True

    # 查询工单与标准件是否匹配CF2 CF3是否有效
    item_code = get_item_code(form1_infos['MoID'])
    days = get_days(form1_infos['StandardPartID'])
    df_special = pd.read_excel("ini/型号.xlsx", header=0)
    list_model = list(df_special['StandardpartID'])
    # 调用getcobspec中定义的get_cf函数,获得cf的值
    if item_code:
        CF2_pars = get_cf(item_code, 2)
        CF3_pars = get_cf(item_code, 3)
    else:
        CF2_pars = pd.DataFrame()
        CF3_pars = pd.DataFrame()

    # 获取工单对应的温度
    temper_1 = get_cold_or_hot(form1_infos['MoID'])
    # 获取标准件对应温度
    temper_2 = get_Temperture(form1_infos['StandardPartID'])

    # 定义sql语句,进行工单与标准件型号的验证
    cursor.execute(
        "SELECT  T1.DOC_NO,T2.ITEM_CODE,T2.ITEM_NAME,T2.FEATURE_NAME,T2.FEATURE_VALUE_DESC FROM MO_ITEM as T1,"
        "ITEM_CODE_VALUE as T2 WHERE T1.ITEM_CODE=T2.ITEM_CODE "
        f"AND T1.DOC_NO='{form1_infos['MoID']}' AND FEATURE_VALUE_DESC='{form1_infos['StandardPartID']}';")
    rows = cursor.fetchall()

    # 椭圆标准只有一部分，进行判断
    df_color = get_color_stand(item_code)
    flag1 = False
    if not df_color.empty:
        for i in df_color.itertuples():
            for column in ['CIEx', 'CIEy', 'a', 'b', 'θ']:
                # 判断颜色标准是否含有空值
                if getattr(i, column) is None or pd.isna(getattr(i, column)):
                    flag1 = True

    type = get_standardPart_type(form1_infos['StandardPartID'])
    if type.empty:
        flash_result[99] = '标准件无有效数据,联系实验室进行更新'
        logger.warn(f"{form1_infos['StandardPartID']}-标准件无有效数据")
    elif len(set(type['StandardPart_Type'])) > 1:
        flash_result[99] = '标准件存在两种类型,联系实验室进行跟进'
        logger.warn(f"{form1_infos['StandardPartID']}-标准件存在两种有效类型")
    # 一次性标准件进行工单号的验证
    elif '一次性' in list(type['StandardPart_Type']) and form1_infos['MoID'] not in list(type['MoID'])[0]:
        flash_result[1] = '一次性标准件存储工单号不对应<br><small>如果比对后发现工单号与标准件对应,请联系实验室进行标准件更新！</small>'
        logger.warn(f"{form1_infos['MachineID']}号设备,工单号与一次性标准件不对应")
    elif not rows:
        flash_result[2] = '工单与标准件不对应,请检查！！'
        logger.warn(f"{form1_infos['MachineID']}号设备,工单标准件不对应")
    elif CF2_pars.empty or CF3_pars.empty:
        flash_result[3] = f"CF2为{not CF2_pars.empty}，CF3为{not CF3_pars.empty}"
        logger.warn(f"{form1_infos['MachineID']}号设备,CF2为{not CF2_pars.empty}，CF3为{not CF3_pars.empty}")
    # 调用getcobspec中的get_spec_range函数获得有效电压范围
    elif item_code and get_spec_range(item_code).query("Parameter == 'ForwardVoltage_V'").empty:
        flash_result[4] = "SpecRange表格无有效电压范围数据,找研发负责人"
        logger.warn(f"{form1_infos['MachineID']}号设备,SpecRange表格无有效电压范围数据")
    # 调用getcobspec中的get_color_stand函数获得颜色标准
    elif flag1:
        flash_result[5] = "Color_Standard表格无有效颜色标准数据,找研发负责人"
        logger.warn(f"{form1_infos['MachineID']}号设备,Color_Standard表格无有效颜色标准数据")

    # 设置条件检验工单温度与标准件温度
    elif form1_infos['StandardPartID'].startswith('CG') and (
            not temper_1 or not temper_2 or abs(float(temper_1) - float(temper_2)) > 10):
        flash_result[6] = "标准件冷热态不对应工单,联系实验室进行跟进"
        logger.warn(f"{form1_infos['MachineID']}号设备,标准件冷热态不对应工单")
        # 该标准件不在分光中
    elif days is None and get_flag(form1_infos['StandardPartID']):
        flash_result[7] = "标准件无有效数据"
    elif form1_infos['StandardPartID'] not in list_model and days > 20 and get_flag(form1_infos['StandardPartID']):
        flash_result[8] = "该标准件已过期，请联系实验室进行更新"
    elif form1_infos['StandardPartID'] in list_model and days > 10 and get_flag(form1_infos['StandardPartID']):
        flash_result[9] = "该标准件已过期，请联系实验室进行更新"
    else:
        # 查询标准件数据是否存在有效数据,并且电压为标准件最大值基础上+5
        cursor.execute("SELECT StandardPartID,AVG(Current_mA), MAX(ForwardVoltage_V)+5 FROM StandardPartData "
                       f"WHERE StandardPartID='{form1_infos['StandardPartID']}' "
                       f"and DataStatus=1 GROUP by StandardPartID")
        rows = cursor.fetchall()
        if not rows:
            flash_result[100] = '标准件无有效数据'
            initconf_path = None
            lotID = None
            logger.warn(f"{form1_infos['MachineID']}号设备,标准件-{form1_infos['StandardPartID']}-无有效数据")
        else:
            current = rows[0][1]
            voltage = rows[0][2]
            logger.info(f"{form1_infos['MachineID']}号设备使用电流：{current}, 电压：{voltage}\n"
                        f"标准件名称：{form1_infos['StandardPartID']},工单号：{form1_infos['MoID']}")
            # 查询对于工单的LOTID是否存在，存在+1，不存在初始化为1
            cursor.execute(
                f"SELECT MAX(LOTID) FROM Precal_Info1 WHERE MOID='{form1_infos['MoID']}';")
            rows = cursor.fetchall()
            if rows[0][0] is None:
                lotID = 1
            else:
                lotID = rows[0][0] + 1

            # 添加LOTID到列表
            form1_infos['LotID'] = lotID

            # 创建上传与下载目录并添加到列表
            uploadsDir = os.path.join('uploads', 'position', str(datetime.now().year), str(datetime.now().month))
            if not os.path.exists(uploadsDir):
                os.makedirs(uploadsDir)
            downloadsDir = os.path.join('downloads', 'initconf', str(datetime.now().year), str(datetime.now().month))
            if not os.path.exists(downloadsDir):
                os.makedirs(downloadsDir)

            # 修改上传文件名并保存
            ext = os.path.splitext(form1_infos['temp_path'])[1]
            upnew_filename = 'position-' + form1_infos['MoID'] + '-' + str(lotID) + ext
            form1_infos['UploadPath'] = os.path.join(uploadsDir, upnew_filename)
            shutil.copy(form1_infos['temp_path'], form1_infos['UploadPath'])

            # 读取初始化配置文件
            try:
                ini_file_read(r".\ini\init6.ini")
                position_file_read(form1_infos['UploadPath'])
                # 移除position和clamp章节,读取上传配置文件的position和clamp章节并赋值给初始化配置文件
                set_position()
                # 修改配置文件的电流电压
                set_voltage_current(voltage, current)

                # 设置颜色标准
                set_color_stand(get_color_stand(item_code))
                # 将修改后的配置文件另存为
                down_filename = '配置-' + form1_infos['MoID'] + '-' + str(lotID) + '.ini'
                initconf_path = os.path.join(downloadsDir, down_filename)
                ini_file_save(initconf_path)

                form1_infos['DownloadPath'] = initconf_path

                # 删除字典temp_path及临时文件
                os.remove(form1_infos.pop('temp_path'))
            except Exception as e:
                flash_result[80] = f'使用错误的配置文件上传！问题描述：{e}'
                logger.error("使用错误的配置文件上传")
            else:
                # 插入当前时间
                form1_infos['UpdateTime'] = str(datetime.now())
                # 遍历字典
                kvs = [(k, v) for k, v in form1_infos.items() if v is not None]
                # 创建sql语句
                sql_data = f"INSERT INTO Precal_Info1({','.join(i[0] for i in kvs)}) " \
                           f"VALUES ({','.join(repr(i[1]) for i in kvs)});"
                try:
                    cursor.execute(sql_data)
                    cnxn.commit()
                except Exception as e:
                    flash_result[99] = f'工单信息存储失败！问题描述：{e}'
                    logger.error(f"数据库Precal_Info1表插入失败，{e}")
                else:
                    flash_result['成功'] = '配置生成成功'
                    logger.info(f"{form1_infos['MachineID']}号设备, {form1_infos['MoID']}配置生成成功-{initconf_path}")
    return flash_result, initconf_path, lotID


if __name__ == '__main__':
    # mo_id = '5101-20060005'
    # standard_part = 'MY2148-033-1210-M3080'
    # mo_id = '5101-20040024'
    # standard_part = 'L2128-007-0702-R3080'
    form1_infos = {'MoID': '5101-20060005', 'MachineID': 0, 'UserID': '10223', 'ProcessID': '1',
                   'StandardPartID': 'MY2148-033-1210-M3080',
                   'temp_path': 'uploads\\temp\\input.ini',
                   'UploadOriginalFileName': 'init00.ini'}
    # print(config_precal(form1_infos))
